'use client'

import { useEffect, useState } from 'react'
import { Button } from '@/components/ui/button'
import { Download } from 'lucide-react'
import * as XLSX from 'xlsx'
import { format } from 'date-fns'
import { zhCN } from 'date-fns/locale'

type TimeRange = 'day' | 'week' | 'month' | 'custom'
type MetricType = 'newUsers' | 'activeUsers' | 'totalUsers'

interface TrendData {
  date: string
  newUsers: number
  activeUsers: number
  totalUsers: number
}

interface Props {
  metrics: MetricType[]
  timeRange: TimeRange
  dateRange?: {
    from: Date
    to: Date
  }
}

const metricLabels = {
  newUsers: '新增用户数',
  activeUsers: '活跃用户数',
  totalUsers: '累计用户数',
}

const formatNumber = (num: number) => {
  return new Intl.NumberFormat('zh-CN').format(num)
}

const formatDateToString = (date: Date) => {
  const year = date.getFullYear()
  const month = (date.getMonth() + 1).toString().padStart(2, '0')
  const day = date.getDate().toString().padStart(2, '0')
  return `${year}-${month}-${day}`
}

export function UserTrendTable({ metrics, timeRange, dateRange }: Props) {
  const [data, setData] = useState<TrendData[]>([])
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(true)
        setError(null)

        let startDate, endDate
        const now = new Date()
        const today = formatDateToString(now)

        switch (timeRange) {
          case 'day': {
            startDate = today
            endDate = today
            break
          }
          case 'week': {
            const start = new Date(now)
            start.setDate(now.getDate() - 6)
            startDate = formatDateToString(start)
            endDate = today
            break
          }
          case 'month': {
            const currentYear = now.getFullYear()
            const currentMonth = now.getMonth() + 1
            startDate = `${currentYear}-${currentMonth.toString().padStart(2, '0')}-01`
            endDate = today
            break
          }
          case 'custom': {
            if (!dateRange?.from || !dateRange?.to) {
              throw new Error('请选择日期范围')
            }
            startDate = formatDateToString(dateRange.from)
            endDate = formatDateToString(dateRange.to)
            break
          }
        }

        const response = await fetch(
          `/api/user-trend?startDate=${startDate}&endDate=${endDate}`,
          {
            headers: {
              'Accept': 'application/json',
            }
          }
        )

        if (!response.ok) {
          throw new Error('获取数据失败')
        }

        const responseData = await response.json()
        setData(responseData)
      } catch (error) {
        console.error('Error fetching trend data:', error)
        setError(error instanceof Error ? error.message : '获取数据失败')
      } finally {
        setLoading(false)
      }
    }

    fetchData()
  }, [timeRange, dateRange])

  const handleDownload = () => {
    const exportData = data.map(item => ({
      '日期': format(new Date(item.date), 'yyyy年MM月dd日', { locale: zhCN }),
      ...metrics.reduce((acc, metric) => ({
        ...acc,
        [metricLabels[metric]]: item[metric]
      }), {})
    }))

    const ws = XLSX.utils.json_to_sheet(exportData)
    const wb = XLSX.utils.book_new()
    XLSX.utils.book_append_sheet(wb, ws, '用户趋势数据')
    
    const fileName = `用户趋势数据_${timeRange}_${new Date().toISOString().split('T')[0]}.xlsx`
    XLSX.writeFile(wb, fileName)
  }

  if (error) {
    return (
      <div className="h-[400px] flex items-center justify-center text-red-500">
        {error}
      </div>
    )
  }

  if (loading) {
    return (
      <div className="h-[400px] flex items-center justify-center">
        加载中...
      </div>
    )
  }

  return (
    <div className="mt-6 space-y-4">
      <div className="flex justify-end">
        <Button
          variant="outline"
          size="sm"
          onClick={handleDownload}
          className="flex items-center gap-2"
        >
          <Download className="w-4 h-4" />
          下载表格
        </Button>
      </div>
      <div className="border rounded-lg">
        <table className="w-full">
          <thead>
            <tr className="border-b bg-gray-50">
              <th className="text-left p-4">日期</th>
              {metrics.map(metric => (
                <th key={metric} className="text-right p-4">
                  {metricLabels[metric]}
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {data.map((item) => (
              <tr key={item.date} className="border-b last:border-0">
                <td className="p-4">
                  {format(new Date(item.date), 'yyyy年MM月dd日', { locale: zhCN })}
                </td>
                {metrics.map(metric => (
                  <td key={metric} className="text-right p-4">
                    {formatNumber(item[metric])}
                  </td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  )
} 